﻿using System;
using System.Text;

namespace YanZhiwei.DotNet2.Utilities.Common
{
    /// <summary>
    ///Exception帮助类
    /// </summary>
    public static class ExceptionHelper
    {
        #region 格式化异常信息提示
        /// <summary>
        /// 格式化异常信息提示
        ///<para>格式:辅助信息_ParamName_Message</para> 
        /// </summary>
        /// <param name="ex">Exception</param>
        /// <param name="auxiliaryText">辅助提示信息</param>
        /// <param name="messageHanlder">委托</param>
        /// <returns>格式化异常信息</returns>
        public static string Builder_Auxiliary_ParamName_Message(this Exception ex, string auxiliaryText, Func<string, string> messageHanlder)
        {
            StringBuilder _builder = new StringBuilder();
            if (ex is ArgumentException)
            {
                ArgumentException _exArgu = (ArgumentException)ex;
                _builder.AppendFormat("{0}{1} {2}", auxiliaryText, _exArgu.ParamName, messageHanlder(_exArgu.Message));
            }
            else
            {
                _builder.AppendFormat("{0} {1}", auxiliaryText, messageHanlder(ex.Message));
            }
            return _builder.ToString();
        }
        #endregion 
        #region  格式化异常消息
        /// <summary>
        /// 格式化异常消息
        /// </summary>
        /// <param name="e">异常对象</param>
        /// <param name="isHideStackTrace">是否隐藏异常规模信息</param>
        /// <returns>格式化后的异常信息字符串</returns>
        public static string FormatMessage(this Exception e, bool isHideStackTrace)
        {
            StringBuilder _builder = new StringBuilder();
            int _count = 0;
            string _appString = string.Empty;
            while (e != null)
            {
                if (_count > 0)
                {
                    _appString += "  ";
                }
                _builder.AppendLine(string.Format("{0}异常消息：{1}", _appString, e.Message));
                _builder.AppendLine(string.Format("{0}异常类型：{1}", _appString, e.GetType().FullName));
                _builder.AppendLine(string.Format("{0}异常方法：{1}", _appString, (e.TargetSite == null ? null : e.TargetSite.Name)));
                _builder.AppendLine(string.Format("{0}异常源：{1}", _appString, e.Source));
                if (!isHideStackTrace && e.StackTrace != null)
                {
                    _builder.AppendLine(string.Format("{0}异常堆栈：{1}", _appString, e.StackTrace));
                }
                if (e.InnerException != null)
                {
                    _builder.AppendLine(string.Format("{0}内部异常：", _appString));
                    _count++;
                }
                e = e.InnerException;
            }
            return _builder.ToString();
        }
        #endregion 
    }
}
